package com.ruijie.acl.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import com.ruijie.acl.AccessGroup;
import com.ruijie.acl.AclPlanParameters;
import com.ruijie.acl.TimeInfo;
import com.ruijie.acl.TimeRange;
import com.ruijie.acl.service.AccessGroupService;
import com.ruijie.acl.service.AceService;
import com.ruijie.acl.service.TimeInfoService;
import com.ruijie.acl.service.TimeRangeService;
import com.ruijie.acl.task.TaskAclUtil;
import com.ruijie.acl.type.AclPlanTypeEnum;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.acl.web.config.Constants;
import com.ruijie.emp.device.Device;
import com.ruijie.foundation.bo.EntityObject;
import com.ruijie.foundation.dao.support.Page;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.service.Repository;
import com.ruijie.foundation.utils.StringUtils;
import com.ruijie.foundation.web.intercept.AddSuccessInfo;

/**
 * <p>
 * Title: ACL组管理Action类




 * 
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * 为ACL组管理模块提供页面数据的显示、获取和页面的跳转。




 * 
 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time:
 * </p>
 * <p>
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * 
 * @author ASAI
 */
@Name("accessGroupAction")
@Scope(ScopeType.CONVERSATION)
@AddSuccessInfo
public class AccessGroupAction extends AclPlanBaseAction {

	@In("#{aceService}")
	private AceService aceService;
	@In(value = "#{facesContext}")
	private FacesContext facesContext;

	@In("#{timeRangeService}")
	private TimeRangeService timeRangeService;
	@In("#{timeInfoService}")
	private TimeInfoService timeInfoService;

	@In("#{accessGroupService}")
	private AccessGroupService accessGroupService;
	
	private AccessGroup criteria = new AccessGroup();

	private AccessGroup model;
	// ACL变更警示：是
	private Boolean chkYes = false;
	// ACL变更警示：否
	private Boolean chkNo = false;
	
	//记录哪些ACL组与设备关联
	private String relationAccessGroups;

	@SuppressWarnings("unchecked")
	public String getRelationAccessGroups() {
		if(this.currentPage==null)return null;
		List<AccessGroup> ags=(List<AccessGroup>)this.currentPage.getResult();
		StringBuffer sb=new StringBuffer();
		for(AccessGroup ag:ags){
			if(this.accessGroupService.isRelated2Device(ag)){
				sb.append(ag.getName()).append(" ");
			}
		}
		if(sb.length()>0){
			relationAccessGroups=sb.substring(0, sb.length()-1);
		}else{
			relationAccessGroups="";
		}
		return relationAccessGroups;
	}
	
	
	/** 
     * <p>Description:  批量删除操作 </p>
     * <p>Create Time: 2008-11-3   </p>
     * @author lusl
     */
	@SuppressWarnings("unchecked")
	@Override
    public void delete() {
		List<AclPlanParameters> paramList = new ArrayList<AclPlanParameters>();	
		Map<Device, String[]> map = new HashMap<Device, String[]>();
		for(Long id:getIds()){
			AccessGroup accessGroup = accessGroupService.get(id);
			/*如果与设备关联*/
			if(accessGroupService.isRelated2Device(accessGroup)){
				List<Device> deviceList = accessGroupService.getDevices(accessGroup);
				for(Device device : deviceList){
					/*如果重复则合并名字*/
					if(map.containsKey(device)){
						//保存ACL组信息

						map.get(device)[0] += ";" + AclUtil.escapeSpecialString(accessGroup.getName()) + "," + accessGroup.getAclType();
						//保存接口信息
						map.get(device)[1] += ";" + accessGroupService.getInterfaceNames(device,accessGroup);
					}else{
						String [] strArr = {"",""};
						//保存ACL组信息
						strArr[0] = AclUtil.escapeSpecialString(accessGroup.getName()) + "," + accessGroup.getAclType();
						//保存ACL组信息
						strArr[1] = accessGroupService.getInterfaceNames(device,accessGroup);;
						
						map.put(device, strArr);
					}
				}
			}
		}
		/*遍历map加入paramList*/
		Iterator iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			Map.Entry entry = (Map.Entry)iterator.next();
			String[] strArr = (String[])entry.getValue();
			Device device = (Device)entry.getKey();
			paramList.add(deleteReDeployment(device,strArr[0], strArr[1]));
		}
       
        if(paramList.size()>0){
        	this.setTaskCode(Constants.ACL_DEPLOY_ACTION_TASK_CODE_DELETE_ACCESSGROUP);
       	 	super.saveAclPlanParameters(paramList);
        } 
        
        super.delete();
    }
	
	/**
	 * 删除组时的重新部署

	 * @param id timeRangeId
	 */
	public AclPlanParameters deleteReDeployment(Device device,String accessGroupString, String interfacesString){
		AclPlanParameters parameters = null;
		parameters = new AclPlanParameters();
		parameters.setAccessGroups(accessGroupString);
		if(!StringUtils.isNullOrEmpty(interfacesString)){
			parameters.setInterfaces(interfacesString);
		}
		parameters.setDevice(device);
		parameters.setDealType(AclPlanTypeEnum.DeleteAccessGroup.toString());
		
		return parameters;
	}


	public void setRelationAccessGroups(String relationAccessGroups) {
		this.relationAccessGroups = relationAccessGroups;
	}

	public void setChkYes(Boolean chkYes) {
		this.chkYes = chkYes;
	}

	public Boolean getChkYes() {
		return this.chkYes;
	}

	public Boolean getChkNo() {
		return chkNo;
	}

	public void setChkNo(Boolean chkNo) {
		this.chkNo = chkNo;
	}

	/**
	 * 取得设备分页信息
	 * 
	 * @return
	 */
	protected Page pagedQuery(EntityObject criteria, int page, int pageSize) {
		AccessGroup groupCriteria = (AccessGroup) criteria;
		// 设置是否已部署ACL：当选择是：已部署；当选择否：未部署

		// 其余情况，全部查询

		if (chkYes) {
			if (!chkNo) {
				groupCriteria.setIsChanged(true);
			} else {
				groupCriteria.setIsChanged(null);
			}
		} else {
			if (!chkNo) {
				groupCriteria.setIsChanged(null);
			} else {
				groupCriteria.setIsChanged(false);
			}
		}

		return accessGroupService.pageQuery(groupCriteria, page, pageSize);
	}

	/**
	 * ACL组导出

	 */
	public void export() {
		facesContext.responseComplete();
		String fileName = "export-" + AclUtil.createUniqueID() + ".txt";

		HttpServletResponse response = (HttpServletResponse) facesContext
				.getExternalContext().getResponse();
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/text");
		response.addHeader("Content-disposition", "attachment; filename=\""
				+ fileName + "\"");
		ServletOutputStream os = null;
		try {
			os = response.getOutputStream();
			/*
			 * 
			 */
			StringBuffer accessGroupText = new StringBuffer();
			StringBuffer timeRangeText = new StringBuffer();
			Set<TimeRange> timeRanges = new HashSet<TimeRange>();
			for (Long id : this.getIds()) {
				AccessGroup accessGroup = accessGroupService.get(id);
				if (accessGroup.getAces() == null
						|| accessGroup.getAces().size() <= 0) {
					accessGroup.setAces(aceService
							.getByAccessGroup(accessGroup));
				}
				// 添加组和规则信息
				accessGroupText.append(TaskAclUtil
						.accessGroup2String(accessGroup));

				// 添加时间段信息




				timeRanges.addAll(this.timeRangeService
						.findByAccessGroup(accessGroup));

			}
			if (timeRanges.size() > 0) {
				for (TimeRange timeRange : timeRanges) {
					if (timeRange.getTimeInfos() == null) {
						// 获取时间段中的时间信息




						List<TimeInfo> infos = this.timeInfoService
								.getByTimeRange(timeRange);
						Set<TimeInfo> sets = new HashSet<TimeInfo>();
						sets.addAll(infos);
						timeRange.setTimeInfos(sets);
					}
					timeRangeText.append(TaskAclUtil
							.timeRange2String(timeRange));
				}
			}
			os.write(timeRangeText.toString().getBytes());
			os.write(accessGroupText.toString().getBytes());
		} catch (BusinessException be) {
			addGlobalI18nMessage(be.getMessage());
		} catch (IOException e) {
			addGlobalI18nMessage("emp_system_deviceGroupExport_exportError");
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (Exception _ignore) {
				}
			}
		}
	}
	
	/**
	 * ACL组详细界面的多设备部署

	 * @param id timeRangeId
	 */
	public void reDeploy(){
		AccessGroup accessGroup = accessGroupService.get(this.getModel().getId());
		List<Device> deviceList = accessGroupService.getDevices(accessGroup);
		List<AclPlanParameters> paramList = new ArrayList<AclPlanParameters>();
		for(Device device:deviceList){
			AclPlanParameters parameters = new AclPlanParameters();
			parameters.setAccessGroups(String.valueOf(accessGroup.getId()));
			parameters.setInterfaces(accessGroupService.getInterfaceIds(device, accessGroup));
			parameters.setInterfacesLog("");
			parameters.setDevice(device);
			parameters.setDealType(AclPlanTypeEnum.ReDeployAccessGroup.toString());
			
			paramList.add(parameters);
		}
		this.setTaskCode(Constants.ACL_DEPLOY_ACTION_TASK_CODE_REDEPLOY_ACCESSGROUP);
		super.saveAclPlanParameters(paramList);
		accessGroup.setIsChanged(false);
		accessGroupService.update(accessGroup);
//		/*保存时间段与设备的关联*/
//		for(Device device:deviceList){
//			deviceTimeRangeService.saveAclDeviceTimeRange(accessGroup, device);
//		}
		// 更新所有不一致设备全部ACL组副本。

//		List<AclDeviceAccessGroup> aclDeviceAccessGroupList = deviceAccessGroupService.findByAccessGroupAndChanged(accessGroup);
//		for(AclDeviceAccessGroup aclDeviceAccessGroup : aclDeviceAccessGroupList){
//			accessGroupService.saveSameWithAclDevice(accessGroup,aclDeviceAccessGroup.getAclDevice(),null);
//		}
//		deviceAccessGroupService.updateChangedByAccessGroup(accessGroup);
		this.setModel(accessGroup);
		addGlobalI18nMessage("acl_redeploy_plan_create_success");
	}
	
	
	/**
	 * 导航至导出页面

	 * 
	 * @return
	 */
	public String toExportPage() {
		return "/acl/accessGroupExport.seam";
	}

	public String toImportPage(){
		return "/acl/accessGroupImport.seam";
	}
	
	@Override
	@SuppressWarnings("unchecked")
	protected Repository getRepository() {
		return accessGroupService;
	}

	@Override
	protected String getAddPage() {
		return "/acl/accessGroupAdd.seam";
	}

	@Override
	public EntityObject getCriteria() {
		return criteria;
	}

	@Override
	protected String getDetailPage() {
		return "/acl/accessGroupDetail.seam";
	}

	@Override
	protected String getListPage() {
		return "/acl/accessGroupIndex.seam";
	}

	@Override
	public EntityObject getModel() {
		model.setDeleteFlg(false);
		return model;
	}

	@Override
	protected String getUpdatePage() {
		return "/acl/accessGroupEdit.seam";
	}

	@Override
	public void resetModel() {
		model = null;
		model = new AccessGroup();
		this.model.setIsChanged(false);
	}

	@Override
	public void setCriteria(EntityObject criteria) {
		this.criteria = (AccessGroup) criteria;
	}

	@Override
	public void setModel(EntityObject model) {
		this.model = (AccessGroup) model;
	}
	
	public void resetNewestModel(){
		try{
			AccessGroup newestModel = accessGroupService.get(this.model.getId());
			this.setModel(newestModel);
		}catch(Exception ex){
			//
		}
	}
	
	//-------------modify by sinyee 2010-10-22 being----------------

	public String toAddPageBlank(){
		this.toAddPage();
		return null;
	}
	
	@AddSuccessInfo
	public String addEntity(){
		this.add();
		return null;
	}

	public String toUpdatePageBlank(EntityObject model){
		this.toUpdatePage(model);
		return null;
	}
	
	@AddSuccessInfo
	public String updateEntity(){
		this.update();
		return null;
	}
	
	public String toDetailPageBlank(EntityObject model,String previousPage){
		this.toDetailPage(model, previousPage);
		return null;
	}
	
	//--------------modify by sinyee 2010-10-22 end----------------
	
	
}
